﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;

namespace IPCByMessages
{
    public class SyncServerMesagesChannel : SyncMessagesChannelBase, IMessagesChannel
    {
        /// <summary>
        /// Gets whether current IMessagesChannel realization is server or client.
        /// For that class (SyncServerMesagesChannel) it's always true.
        /// </summary>
        public bool IsServerSide { get { return true; } }

        /// <summary>
        /// Setup server connection at specified port
        /// </summary>
        /// <param name="port">Port to connect</param>
        internal SyncServerMesagesChannel(int port)
        {
            try
            {
                connection = new Socket(AddressFamily.InterNetwork,
                    SocketType.Stream,
                    ProtocolType.Tcp);

                var adress = Dns.GetHostAddresses(Environment.MachineName)[0];
                var endPoint = new IPEndPoint(adress, port);

                connection.Bind(endPoint);
                connection.Listen(1);

                connection.SendBufferSize =
                    connection.ReceiveBufferSize = 655360;

                StartToAccept();
            }
            catch
            {
                Close();
                throw;
            }
        }

        #region Setup

        /// <summary>
        /// Start to accept incoming connections
        /// </summary>
        private void StartToAccept()
        {
            connection.BeginAccept(AcceptCallback, null);
        }

        /// <summary>
        /// Callback for incoming connection setup
        /// </summary>
        /// <param name="res">Result</param>
        private void AcceptCallback(IAsyncResult res)
        {
            if (!((otherSide != null) && otherSide.Connected))
            {
                if (otherSide != null)
                {
                    otherSide.Close();
                    otherSide = null;
                }

                otherSide = connection.EndAccept(res);

                otherSide.SendBufferSize =
                    otherSide.ReceiveBufferSize = 65536;

                Active = true;
                BeginReceive();
            }
            StartToAccept();
        }
        
        #endregion
    }
}
